package test.serverframe.armc.server.manager.controller;

import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import test.serverframe.armc.server.manager.common.ResultDtoUtil;
import test.serverframe.armc.server.manager.common.exception.ExceptionHandle;
import test.serverframe.armc.server.manager.controller.vo.InterfaceParamHistoryVo;
import test.serverframe.armc.server.manager.controller.vo.TaskHistoryVo;
import test.serverframe.armc.server.manager.domain.Task;
import test.serverframe.armc.server.manager.domain.params.AddAllData;
import test.serverframe.armc.server.manager.domain.params.HistoryInterfaceParams;
import test.serverframe.armc.server.manager.domain.params.HistoryRecordParam;
import test.serverframe.armc.server.manager.domain.params.TaskParams;
import test.serverframe.armc.server.manager.dto.ResultDto;
import test.serverframe.armc.server.manager.service.TaskService;
import test.serverframe.armc.server.manager.service.impl.InterfaceInvokingRecordService;
import test.serverframe.armc.server.manager.service.impl.InvokeTaskRecordServiceImpl;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description 任务管理
 * @Author LSY
 * @Date 2018/9/26 15:44
 * @ClassName test.serverframe.armc.server.manager.controller.ServerPlanController
 */
@CrossOrigin(origins = "*")
@Api("任务管理")
@Validated
@RequestMapping("/task")
@RestController
public class TaskManagerController {
	
	private Logger logger = LoggerFactory.getLogger(TaskManagerController.class);

    /**
     * 任务服务
     */
    @Autowired
    private TaskService taskService;
    
    @Autowired
    private InvokeTaskRecordServiceImpl taskRecordService;

    /**
     * 任务分页自定义异常
     */
    @Autowired
    private ExceptionHandle<PageInfo<Task>> exceptionHandle;
    
    @Autowired
    InterfaceInvokingRecordService interfaceRecordService;

    /**
     * @Descripttion 任务分页
     * @Author LSY
     * @Date 2018/9/26 17:16
     * @Param [ data 任务查询条件实体]
     * @Return
     **/
    @GetMapping("/page")
    @ApiOperation(notes = "任务分页查询", value = "任务分页查询")
    public ResultDto<PageInfo<Task>> taskPages(@ModelAttribute @Valid TaskParams data) {
        ResultDto<PageInfo<Task>> result;
        try {
            PageInfo<Task> mbrValues = taskService.pageFind(data.getPageNum(), data.getPageSize(), data);
            result = ResultDtoUtil.success(mbrValues);
        } catch (Exception ex) {
            result = exceptionHandle.exceptionGet(ex);
            logger.error("任务分页查询", ex);
        }
        return result;
    }

    /**
     * @Descripttion 查看任务详情
     * @Author LSY
     * @Date 2018/10/5 16:03
     * @Param [task 对象，只用传任务id]
     * @Return
     **/
    @GetMapping("{id}")
    @ApiOperation(notes = "查看任务详情", value = "查看任务详情")
    public ResultDto<AddAllData> findTask(@ApiParam("主键id") @PathVariable String id) {
        ResultDto<AddAllData> result;
        try {
            AddAllData customTask = taskService.findTask(id);
            result = ResultDtoUtil.success(customTask);
        } catch (Exception ex) {
            result = ResultDtoUtil.error(500, "查看任务详情错误");
            ex.printStackTrace();
        }
        return result;
    }

    /**
     * @Descripttion 新增任务
     * @Author LSY
     * @Date 2018/10/5 14:54
     * @Param [addAllData 自定义数据格式]
     * @Return
     **/
    @PostMapping("/add")
    @ApiOperation(notes = "新增任务", value = "新增任务")
    public ResultDto<Integer> addTaskInterface(@ApiParam("自定义任务实体") @RequestBody AddAllData addAllData) {
        ResultDto<Integer> result;
        try {
        	//任务名称去重
        	for (String taskName : taskService.findTaskName()) {
        		if (addAllData.getTaskName().equals(taskName)) {
        			return ResultDtoUtil.error(500, "任务名称重复，重新设置");
        		}
        	}
            taskService.addTask(addAllData);
            result = ResultDtoUtil.success(200);
        } catch (Exception ex) {
            result = ResultDtoUtil.error(500, "新增任务接口错误");
            logger.error("新增任务接口错误", ex);
        }
        return result;
    }

    /**
     * @Descripttion 修改任务
     * @Author LSY
     * @Date 2018/9/27 17:24
     * @Param [addAllData 自定义数据格式]
     * @Return 修改成功数量
     **/
    @PostMapping("/modify")
    @ApiOperation(notes = "修改任务", value = "修改任务")
    public ResultDto<Integer> updateTask(@ApiParam("自定义任务实体") @RequestBody @Valid AddAllData addAllData) {
        ResultDto<Integer> result;
        try {
        	//逻辑删除原来的任务
        	Task task = new Task();
        	task.setIsUsed(false);
        	task.setTaskId(addAllData.getTaskId());
        	taskService.updateByPrimaryKeySelective(task);
        	//新增任务
            int i = taskService.addTask(addAllData);
            result = ResultDtoUtil.success(i);
        } catch (Exception ex) {
            ex.printStackTrace();
            result = ResultDtoUtil.error(500, "修改任务错误");
            logger.error("修改任务错误", ex);
            
        }
        return result;
    }

    /**
     * @Descripttion 批量删除任务
     * @Author LSY
     * @Date 2018/9/29 13:53
     * @Param [task 任务实体，只需要传任务id集合]
     * @Return
     **/
    @DeleteMapping("/delete")
    @ApiOperation(notes = "批量删除任务", value = "批量删除任务")
    public ResultDto<Integer> deleteTask(@RequestBody List<String> ids) {
        ResultDto<Integer> result;
        try {
            ids.forEach(id -> {
                Task task = new Task();
                task.setIsUsed(false);
                task.setTaskId(id);
                taskService.updateByPrimaryKeySelective(task);
            });
            result = ResultDtoUtil.success();
        } catch (Exception ex) {
            result = ResultDtoUtil.error(500, "批量删除任务错误");
        }
        return result;
    }

    @GetMapping("/exception/handles")
    @ApiOperation(notes = "获取异常处理策略列表", value = "获取异常处理策略列表")
    public Map<Integer, String> getExceptionHandles() {
        Map<Integer, String> handles = new HashMap<>(3);
        handles.put(0, "跳过");
        handles.put(1, "终止任务");
        return handles;
    }
    
    
    /**
	 *  获取调度历史详情中的任务名称和任务执行顺序
	 * @author yegui  
	 * @date 2018年12月14日  
	 * @param params  查询参数模型
	 * @return 调度历史详情中的任务名称和任务执行顺序
	 * List<TaskHistoryVo>
	 */
    @PostMapping("/getTaskRecord")
    @ApiOperation(notes = "查看历史任务详情", value = "查看历史任务详情")
    public ResultDto<TaskHistoryVo> getTaskRecord(@ApiParam @RequestBody HistoryRecordParam params) {
        ResultDto<TaskHistoryVo> result;
        try {
        	TaskHistoryVo taskHistoryVo = taskRecordService.getTaskRecord(params);
            result = ResultDtoUtil.success(taskHistoryVo);
        } catch (Exception ex) {
            result = ResultDtoUtil.error(500, "查看任务详情错误");
            ex.printStackTrace();
        }
        return result;
    }

    /*
     * 获取历史接口调用关系
     * @author yegui  
     * @date 2018年12月18日  
     * @param param
     * @return
     * ResultDto<AddAllData>
     */
    @PostMapping("/historyInterface")
    @ApiOperation(notes = "查看历史接口详情", value = "查看历史接口详情")
    public ResultDto<TaskHistoryVo> findTistoryTask(@ApiParam @RequestBody HistoryInterfaceParams param) {
        ResultDto<TaskHistoryVo> result;
        try {
        	TaskHistoryVo vo = interfaceRecordService.findInterfaceParamsHistory(param);
            result = ResultDtoUtil.success(vo);
        } catch (Exception ex) {
            result = ResultDtoUtil.error(500, "查看任务历史详情错误");
            ex.printStackTrace();
        }
        return result;
    }



}


